package view_server

import (
	"bigdevops/src/cache"
	"bigdevops/src/common"
	"bigdevops/src/config"
	"bigdevops/src/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	appsv1 "k8s.io/api/apps/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/json"
	"k8s.io/client-go/kubernetes"
	"sigs.k8s.io/yaml"

	"sort"
	"strconv"
	"strings"
	"time"
)

func getK8sDeployListByNs(c *gin.Context) {

	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)

	currentPage, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))
	sortFiled := c.DefaultQuery("field", "")
	orderType := c.DefaultQuery("order", "")

	// 集群的名称
	searchCluster := c.DefaultQuery("cluster", "")
	searchName := c.DefaultQuery("name", "")

	searchNamespace := c.DefaultQuery("namespace", "")
	if searchNamespace == common.K8S_NS_ALL_KEY {
		searchNamespace = ""
	}

	if searchCluster == "" {
		msg := "集群名称未传入"
		sc.Logger.Error(msg)
		common.ReqBadFailWithMessage(msg, c)
		return
	}

	dbObj, err := models.GetK8sClusterByName(searchCluster)
	if err != nil {
		sc.Logger.Error("根据name找k8s集群错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 从cache中通过 集群的id 拿到集群的clientSet
	kc := c.MustGet(common.GIN_CTX_K8s_CACHE).(*cache.K8sClusterCache)
	kSet := kc.GetClusterClientSetById(dbObj.ID)
	if kSet == nil {
		msg := fmt.Sprintf("根据id找k8s集群kset缓存错误")
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	mSet := kc.GetClusterMetricsClientSetById(dbObj.ID)
	if mSet == nil {
		sc.Logger.Error("根据id找k8s集群metricsSet缓存错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	ctx1, cancel1 := common.GenTimeoutContext(dbObj.ActionTimeoutSeconds)
	defer cancel1()
	deployItems, err := kSet.AppsV1().Deployments(searchNamespace).List(ctx1, metav1.ListOptions{})
	if err != nil {
		sc.Logger.Error("根据ik8s集群kset获取节点错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 进行搜索
	filterResults := []appsv1.Deployment{}
	for _, dep := range deployItems.Items {
		if searchName != "" && !strings.Contains(dep.Name, searchName) {
			continue
		}
		filterResults = append(filterResults, dep)

	}

	//startIndex, endIndex
	startIndex := (pageSize) * (currentPage - 1)
	endIndex := startIndex + pageSize
	if endIndex > len(filterResults) {
		endIndex = len(filterResults)
	}

	// 转化一下
	finalRes := []*OneDeployment{}
	pageResult := filterResults[startIndex:endIndex]

	for _, obj := range pageResult {
		one := deployConvert(obj, dbObj, kSet, true)
		finalRes = append(finalRes, one)
	}
	// 排序
	if sortFiled == "name" {

		sort.SliceStable(finalRes, func(i, j int) bool {
			if orderType == "ascend" {
				return finalRes[i].Name < finalRes[j].Name
			} else {
				return finalRes[i].Name > finalRes[j].Name
			}

		})
	}

	resp := &ResponseResourceCommon{
		//Total: models.GetK8sClusterCount(), 因为是带了查询条件的 所以 count 不能是all 而是 过滤后的total

		Total: len(filterResults),
		Items: finalRes,
	}

	common.OkWithDetailed(resp, "ok", c)
}

/*
root@k8s-master01:~# kubectl get deploy -o wide  -A
NAMESPACE              NAME                        READY   UP-TO-DATE   AVAILABLE   AGE    CONTAINERS                  IMAGES                                                                         SELECTOR
calico-apiserver       calico-apiserver            2/2     2            2           125d   calico-apiserver            docker.io/calico/apiserver:v3.26.1                                             apiserver=true
calico-system          calico-kube-controllers     1/1     1            1           125d   calico-kube-controllers     docker.io/calico/kube-controllers:v3.26.1                                      k8s-app=calico-kube-controllers
calico-system          calico-typha                1/1     1            1           125d   calico-typha                docker.io/calico/typha:v3.26.1                                                 k8s-app=calico-typha
default                mysql-57                    1/1     1            1           119d   mysql                       mysql:5.7                                                                      app=mysql-57
default                nginx-bigdevops             1/1     1            1           7d4h   nginx                       nginx:1.7.9                                                                    app=nginx
kube-system            coredns                     2/2     2            2           125d   coredns                     registry.aliyuncs.com/google_containers/coredns:v1.10.1                        k8s-app=kube-dns
kube-system            grafana                     1/1     1            1           49d    grafana                     grafana/grafana:8.5.6                                                          app=grafana
kube-system            kube-state-metrics          1/1     1            1           49d    kube-state-metrics          registry.cn-beijing.aliyuncs.com/ning1875_haiwai_image/ksm:v2.2.4              app.kubernetes.io/name=kube-state-metrics
kube-system            metrics-server              1/1     1            1           14d    metrics-server              registry.cn-beijing.aliyuncs.com/ning1875_haiwai_image/metrics-server:v0.6.4   k8s-app=metrics-server
kubernetes-dashboard   dashboard-metrics-scraper   1/1     1            1           21d    dashboard-metrics-scraper   kubernetesui/metrics-scraper:v1.0.8                                            k8s-app=dashboard-metrics-scraper
kubernetes-dashboard   kubernetes-dashboard        1/1     1            1           21d    kubernetes-dashboard        kubernetesui/dashboard:v2.7.0                                                  k8s-app=kubernetes-dashboard
tigera-operator        tigera-operator             1/1     1            1           125d   tigera-operator             quay.io/tigera/operator:v1.30.4                                                name=tigera-operator
*/
type OneDeployment struct {
	Name        string            `json:"name"`
	Namespace   string            `json:"namespace"`
	Age         string            `json:"age"`
	LabelPairs  map[string]string `json:"labelPairs"`
	Labels      []string          `json:"labels"`
	LabelsFront string            `json:"labelsFront"`
	TaintsFront string            `json:"taintsFront"`
	Containers  []string          `json:"containers"`
	Images      []string          `json:"images"`

	ContainerImages       []string                     `json:"containerImages"`
	ContainerImageOptions []common.CommonSelectOneItem `json:"containerImageOptions"`
	PodLastRestartTime    string                       `json:"podLastRestartTime"`
	ReadyStatus           string                       `json:"readyStatus"`
	UpdatedReplicas       int                          `json:"updatedReplicas"`
	Replicas              int                          `json:"replicas"`
	AvailableReplicas     int                          `json:"availableReplicas"`
	ReadyReplicas         int                          `json:"readyReplicas"`
}

func deployConvert(deploy appsv1.Deployment, kCluster *models.K8sCluster, kSet *kubernetes.Clientset, fetchEvent bool) *OneDeployment {
	res := &OneDeployment{}
	res.Namespace = deploy.Namespace
	res.Name = deploy.Name
	res.Age = translateTimestampSince(deploy.CreationTimestamp)

	// 标签
	res.LabelPairs = deploy.Labels
	res.Labels = common.GenStringArrayByMap(deploy.Labels)
	res.LabelsFront = strings.Join(res.Labels, "\n")

	// 容器
	for _, c := range deploy.Spec.Template.Spec.Containers {
		format := fmt.Sprintf(`容器:%s 镜像:%s`, c.Name, c.Image)
		res.ContainerImages = append(res.ContainerImages, format)
		res.Containers = append(res.Containers, c.Name)
		res.Images = append(res.Images, c.Image)
		res.ContainerImageOptions = append(res.ContainerImageOptions, common.CommonSelectOneItem{
			Label: format,
			Value: c.Name,
		})
	}

	// 几个状态
	desiredReplicas := int(*deploy.Spec.Replicas)
	updatedReplicas := int(deploy.Status.UpdatedReplicas)
	readyReplicas := int(deploy.Status.ReadyReplicas)
	availableReplicas := int(deploy.Status.AvailableReplicas)

	res.UpdatedReplicas = updatedReplicas
	res.AvailableReplicas = availableReplicas
	res.Replicas = desiredReplicas
	res.ReadyReplicas = readyReplicas
	res.ReadyStatus = fmt.Sprintf("%d/%d", readyReplicas, desiredReplicas)
	return res

}

type SetImageRequest struct {
	Cluster   string `json:"cluster"`
	Namespace string `json:"namespace"`
	Container string `json:"container"`
	Name      string `json:"name"`
	Image     string `json:"image"`
}

type ScaleDeploymentRequest struct {
	Cluster   string `json:"cluster"`
	Namespace string `json:"namespace"`
	Name      string `json:"name"`
	Replicas  int    `json:"replicas"`
}

func setDeployOneContainerImage(c *gin.Context) {
	//kset *kubernetes.Clientset, podName string, containerName string, ns string string
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj SetImageRequest
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("解析SetImageRequest配置请求失败", zap.Any("k8s配置", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 在这里校验字段，是否必填，范围是否正确
	err = validate.Struct(reqObj)
	if err != nil {

		// 这里为什么要判断错误是否是 ValidationErrors
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(

				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return

	}

	//searchCluster := c.DefaultQuery("cluster", "")
	searchCluster := reqObj.Cluster
	//searchName := c.DefaultQuery("name", "")
	searchName := reqObj.Name

	//searchNamespace := c.DefaultQuery("namespace", "")
	searchNamespace := reqObj.Namespace
	//searchContainer := c.DefaultQuery("container", "")
	searchContainer := reqObj.Container
	searchImage := reqObj.Image

	if searchCluster == "" {
		msg := "集群名称未传入"
		sc.Logger.Error(msg)
		common.ReqBadFailWithMessage(msg, c)
		return
	}

	dbObj, err := models.GetK8sClusterByName(searchCluster)
	if err != nil {
		sc.Logger.Error("根据name找k8s集群错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 从cache中通过 集群的id 拿到集群的clientSet
	kc := c.MustGet(common.GIN_CTX_K8s_CACHE).(*cache.K8sClusterCache)
	kSet := kc.GetClusterClientSetById(dbObj.ID)
	if kSet == nil {
		msg := fmt.Sprintf("根据id找k8s集群kset缓存错误")
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	ctx1, canFun1 := common.GenTimeoutContext(dbObj.ActionTimeoutSeconds)
	defer canFun1()
	dep, err := kSet.AppsV1().Deployments(searchNamespace).Get(ctx1, searchName, metav1.GetOptions{})
	if err != nil {
		msg := fmt.Sprintf("更新image前获取deploy对象错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	targetIndex := 0
	for index, c := range dep.Spec.Template.Spec.Containers {
		if c.Name == searchContainer {
			targetIndex = index
			break
			//c.Image = searchImage
		}
	}
	cs := dep.Spec.Template.Spec.Containers
	cs[targetIndex].Image = searchImage
	dep.Spec.Template.Spec.Containers = cs

	fmt.Println(reqObj)
	fmt.Println(dep.Spec.Template.Spec.Containers)

	_, err = kSet.AppsV1().Deployments(searchNamespace).Update(ctx1, dep, metav1.UpdateOptions{})
	if err != nil {
		msg := fmt.Sprintf("更新image对象错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	common.OkWithMessage("更新成功", c)

}

func k8sScaleDeployOne(c *gin.Context) {
	//kset *kubernetes.Clientset, podName string, containerName string, ns string string
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj ScaleDeploymentRequest
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("解析ScaleDeploymentRequest配置请求失败", zap.Any("k8s配置", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 在这里校验字段，是否必填，范围是否正确
	err = validate.Struct(reqObj)
	if err != nil {

		// 这里为什么要判断错误是否是 ValidationErrors
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(

				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return

	}

	//searchCluster := c.DefaultQuery("cluster", "")
	searchCluster := reqObj.Cluster
	//searchName := c.DefaultQuery("name", "")
	searchName := reqObj.Name

	//searchNamespace := c.DefaultQuery("namespace", "")
	searchNamespace := reqObj.Namespace
	//searchContainer := c.DefaultQuery("container", "")
	searchReplicas := reqObj.Replicas

	if searchCluster == "" {
		msg := "集群名称未传入"
		sc.Logger.Error(msg)
		common.ReqBadFailWithMessage(msg, c)
		return
	}

	dbObj, err := models.GetK8sClusterByName(searchCluster)
	if err != nil {
		sc.Logger.Error("根据name找k8s集群错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 从cache中通过 集群的id 拿到集群的clientSet
	kc := c.MustGet(common.GIN_CTX_K8s_CACHE).(*cache.K8sClusterCache)
	kSet := kc.GetClusterClientSetById(dbObj.ID)
	if kSet == nil {
		msg := fmt.Sprintf("根据id找k8s集群kset缓存错误")
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	ctx1, canFun1 := common.GenTimeoutContext(dbObj.ActionTimeoutSeconds)
	defer canFun1()
	dep, err := kSet.AppsV1().Deployments(searchNamespace).Get(ctx1, searchName, metav1.GetOptions{})
	if err != nil {
		msg := fmt.Sprintf("更新image前获取deploy对象错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	var tmp int32 = 0
	tmp = int32(searchReplicas)
	var value *int32
	value = &tmp

	dep.Spec.Replicas = value

	_, err = kSet.AppsV1().Deployments(searchNamespace).Update(ctx1, dep, metav1.UpdateOptions{})
	if err != nil {
		msg := fmt.Sprintf("scale-deploy-更新对象错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	common.OkWithMessage("更新成功", c)

}

func k8sBatchDeleteDeploy(c *gin.Context) {
	//kset *kubernetes.Clientset, podName string, containerName string, ns string string
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj common.K8sBatchRequestCommon
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("解析批量删除Deployment请求失败", zap.Any("k8s配置", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 在这里校验字段，是否必填，范围是否正确
	err = validate.Struct(reqObj)
	if err != nil {

		// 这里为什么要判断错误是否是 ValidationErrors
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(

				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return

	}

	//searchCluster := c.DefaultQuery("cluster", "")
	searchCluster := reqObj.Cluster

	if searchCluster == "" {
		msg := "集群名称未传入"
		sc.Logger.Error(msg)
		common.ReqBadFailWithMessage(msg, c)
		return
	}

	dbObj, err := models.GetK8sClusterByName(searchCluster)
	if err != nil {
		sc.Logger.Error("根据name找k8s集群错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 从cache中通过 集群的id 拿到集群的clientSet
	kc := c.MustGet(common.GIN_CTX_K8s_CACHE).(*cache.K8sClusterCache)
	kSet := kc.GetClusterClientSetById(dbObj.ID)
	if kSet == nil {
		msg := fmt.Sprintf("根据id找k8s集群kset缓存错误")
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	for _, item := range reqObj.Items {
		item := item
		ctx1, canFun1 := common.GenTimeoutContext(dbObj.ActionTimeoutSeconds)
		defer canFun1()
		err := kSet.AppsV1().Deployments(item.Namespace).Delete(ctx1, item.Name, metav1.DeleteOptions{})
		if err != nil {
			msg := fmt.Sprintf("删除Deployment错误:ns:%v name:%v %v", item.Namespace, item.Name, err.Error())
			sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
			common.FailWithMessage(msg, c)
			return
		}

	}

	common.OkWithMessage("删除成功", c)

}

func k8sBatchRestartDeploy(c *gin.Context) {
	//kset *kubernetes.Clientset, podName string, containerName string, ns string string
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj common.K8sBatchRequestCommon
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("解析批量重启Deployment请求失败", zap.Any("k8s配置", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 在这里校验字段，是否必填，范围是否正确
	err = validate.Struct(reqObj)
	if err != nil {

		// 这里为什么要判断错误是否是 ValidationErrors
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(

				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return

	}

	//searchCluster := c.DefaultQuery("cluster", "")
	searchCluster := reqObj.Cluster

	if searchCluster == "" {
		msg := "集群名称未传入"
		sc.Logger.Error(msg)
		common.ReqBadFailWithMessage(msg, c)
		return
	}

	dbObj, err := models.GetK8sClusterByName(searchCluster)
	if err != nil {
		sc.Logger.Error("根据name找k8s集群错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 从cache中通过 集群的id 拿到集群的clientSet
	kc := c.MustGet(common.GIN_CTX_K8s_CACHE).(*cache.K8sClusterCache)
	kSet := kc.GetClusterClientSetById(dbObj.ID)
	if kSet == nil {
		msg := fmt.Sprintf("根据id找k8s集群kset缓存错误")
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	for _, item := range reqObj.Items {
		item := item
		ctx1, canFun1 := common.GenTimeoutContext(dbObj.ActionTimeoutSeconds)
		defer canFun1()

		data := fmt.Sprintf(`{"spec": {"template": {"metadata": {"annotations": {"bigdevops/restartedAt": "%s"}}}}}`, time.Now().Format("2006-01-02 15:04:05"))
		//deployment, err := deploymentsClient.Patch(ctx, deployment_name, t.StrategicMergePatchType, []byte(data), v1.PatchOptions{})

		_, err := kSet.AppsV1().Deployments(item.Namespace).Patch(ctx1, item.Name, types.StrategicMergePatchType, []byte(data), metav1.PatchOptions{})
		if err != nil {
			msg := fmt.Sprintf("重启patch-Deployment错误:ns:%v name:%v %v", item.Namespace, item.Name, err.Error())
			sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
			common.FailWithMessage(msg, c)
			return
		}

	}

	common.OkWithMessage("重启成功", c)

}

func getK8sDeployYamlOne(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)

	searchCluster := c.DefaultQuery("cluster", "")
	searchName := c.DefaultQuery("name", "")

	searchNamespace := c.DefaultQuery("namespace", "")
	//searchContainer := c.DefaultQuery("container", "")
	//searchShell := c.DefaultQuery("shell", "bash")

	if searchCluster == "" {
		msg := "集群名称未传入"
		sc.Logger.Error(msg)
		common.ReqBadFailWithMessage(msg, c)
		return
	}

	dbObj, err := models.GetK8sClusterByName(searchCluster)
	if err != nil {
		sc.Logger.Error("根据name找k8s集群错误", zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 从cache中通过 集群的id 拿到集群的clientSet
	kc := c.MustGet(common.GIN_CTX_K8s_CACHE).(*cache.K8sClusterCache)
	kSet := kc.GetClusterClientSetById(dbObj.ID)
	if kSet == nil {
		msg := fmt.Sprintf("根据id找k8s集群kset缓存错误")
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	ctx1, cancel1 := common.GenTimeoutContext(dbObj.ActionTimeoutSeconds)
	defer cancel1()
	deploy, err := kSet.AppsV1().Deployments(searchNamespace).Get(ctx1, searchName, metav1.GetOptions{})
	//fmt.Println(pod)
	deploy.APIVersion = "apps/v1"
	deploy.Kind = "Deployment"
	deploy.ManagedFields = nil

	if err != nil {
		msg := fmt.Sprintf("根据id找k8s集群get-pod错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	jsonBytes, err := json.Marshal(deploy)
	if err != nil {
		msg := fmt.Sprintf("根据pod对象jsonMarshal错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}
	y, err := yaml.JSONToYAML(jsonBytes)
	if err != nil {
		msg := fmt.Sprintf("根据pod对象jsonyaml.JSONToYAML错误:%v", err.Error())
		sc.Logger.Error(msg, zap.Any("k8s集群配置", searchCluster), zap.Error(err))
		common.FailWithMessage(msg, c)
		return
	}

	common.OkWithData(string(y), c)
}
